package classes.multithread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * @author : DuJiabao
 * @Date : 2021/2/9 10:54
 * @Project : java_learning
 * @File : null.java
 * @Desc :
 */
public class ThreadFactoryTest implements Runnable{
  public static void main(String[] args) {
    ExecutorService exec = Executors.newCachedThreadPool(new DaemonThreadFactory());
    for (int i = 0; i < 5; i++) {
      exec.execute(new ThreadFactoryTest());
    }
    try {
      TimeUnit.MILLISECONDS.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void run() {
    try {
      while (true){
        System.out.println(Thread.currentThread().getName());
        TimeUnit.MILLISECONDS.sleep(100);
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

class DaemonThreadFactory implements ThreadFactory {
  /**
   * 对线程线程进行预处理再返还
   *
   * @param r
   * @return
   */
  @Override
  public Thread newThread(Runnable r) {
    Thread thread = new Thread(r);
    thread.setDaemon(true);
    return thread;
  }
}
